package unipd.esp1112.pro;

import java.util.Calendar;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;


/**
 * 
 * Activity where the user can create and edit profiles
 * 
 * @author andrea basso, federico lancerin, alex tomasello
 * 
 */
public class NuovoProfilo extends Activity {

	/**
	 * constants used as delimiters for the values of height and weight accepted by the application
	 */
	final static int MAXHEIGHT = 300;
	final static int MINHEIGHT = 100;
	final static int MAXWEIGHT = 300;
	final static int MINWEIGHT = 30;

	/**
	 * edittext that contains and displays the name of the profile
	 */
	private EditText nome;
	/**
	 * datepicker used to set your birth date
	 */
	private DatePicker datepick;
	/**
	 * edittext that contains and displays the height for the chosen profile
	 */
	private EditText altezza;
	/**
	 * edittext that contains and displays the weight for the chosen profile
	 */
	private EditText peso;
	/**
	 * radiobutton used to set the profile's sex to male
	 */
	private RadioButton radioMaschi;
	/**
	 * radiobutton used to set the profile's sex to female
	 */
	private RadioButton radioFemmine;
	/**
	 * variable used to retrieve an instance of the application private database
	 */
	private MyOpenHelper op;
	/**
	 * variable used to reference the database
	 */
	private SQLiteDatabase db;
	/**
	 * variable used as container for variables that need to be stored in a database
	 */
	private ContentValues values;
	/**
	 * cursor used to retrieve the results of a query
	 */
	private Cursor query;
	/**
	 * variable to store the name of the profile the user is currently using
	 */
	private String nomeProfilo = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nuovoprofilo);

		final TextView name = (TextView) findViewById(R.id.nomeXml);
		final TextView date = (TextView) findViewById(R.id.dataXml);
		final TextView height = (TextView) findViewById(R.id.altezzaXml);
		final TextView weight = (TextView) findViewById(R.id.pesoXml);

		nome = (EditText) findViewById(R.id.editNomeXml);
		radioMaschi = (RadioButton) findViewById(R.id.radioButtonMaschi);
		radioFemmine = (RadioButton) findViewById(R.id.radioButtonFemmine);
		datepick = (DatePicker) findViewById(R.id.datePicker1);
		altezza = (EditText) findViewById(R.id.editAltezzaXml);
		peso = (EditText) findViewById(R.id.editPesoXml);

		// prendo un riferimento all'istanza di database
		op = new MyOpenHelper(this);
		radioMaschi.setChecked(true);

		// se è stato selezionato un profilo da modificare , carico i valori
		// presenti nel database
		Intent intent = getIntent();
		nomeProfilo = intent.getStringExtra("profilo");
		if (nomeProfilo != null) {
			db = op.getWritableDatabase();
			query = db.rawQuery("SELECT * FROM Profilo where nome='" + nomeProfilo + "'", null);
			while (!query.isLast() && !query.isAfterLast()) {
				query.moveToNext();
				nome.setText(query.getString(0));
				nome.setEnabled(false);
				nome.setFocusable(false);
				if (query.getString(1).equals("1"))
					radioMaschi.setChecked(true);
				else {
					radioFemmine.setChecked(true);
					radioMaschi.setChecked(false);
				}
				String[] dataSplit = query.getString(2).split("/");
				datepick.updateDate(Integer.parseInt(dataSplit[2]), Integer.parseInt(dataSplit[1]) - 1, Integer.parseInt(dataSplit[0]));
				altezza.setText(query.getString(3));
				peso.setText(query.getString(4));
			}
			db.close();
		}

		radioMaschi.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked)
					radioFemmine.setChecked(false);
			}
		});

		radioFemmine.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked)
					radioMaschi.setChecked(false);
			}
		});

		Button nuovoProfilo = (Button) findViewById(R.id.newProfileButton);
		if (nomeProfilo != null)
			nuovoProfilo.setText("salva");
		nuovoProfilo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// controllo dei valori proposti dall'utente
				boolean nomeOk = true;
				boolean dataOk = true;
				boolean altezzaOk = true;
				boolean pesoOk = true;

				db = op.getWritableDatabase();
				values = new ContentValues();

				// impongo una lunghezza minima del nome = 3
				if (nome.getText().toString().length() < 3) {
					nomeOk = false;
					name.setTextColor(Color.RED);
				}
				// controllo esistenza profilo con stessa chiave primaria
				if (nomeProfilo == null) {
					query = db.rawQuery("SELECT nome FROM Profilo", null);
					while (!query.isLast() && !query.isAfterLast()) {
						query.moveToNext();
						if (query.getString(0).equalsIgnoreCase(nome.getText().toString())) {
							nomeOk = false;
							name.setTextColor(Color.RED);
						}
					}
					if (nomeOk) {
						name.setTextColor(Color.WHITE);
						values.put(op.NOME, nome.getText().toString());
					}
				}

				// se "Maschio" il valore da inserire nel DB è TRUE, se "Femmina" è FALSE
				if (radioMaschi.isChecked())
					values.put(op.SESSO, true);
				if (radioFemmine.isChecked())
					values.put(op.SESSO, false);

				// impongo un'età minima di 10 anni
				if (datepick.getYear() > (Calendar.getInstance().get(Calendar.YEAR) - 10)) {
					dataOk = false;
					date.setTextColor(Color.RED);
				} else {
					date.setTextColor(Color.WHITE);
					values.put(op.DATANASCITA, datepick.getDayOfMonth() + "/" + (datepick.getMonth() + 1) + "/" + datepick.getYear());
				}

				// impongo altezze minima e massima dichiarabili dall'utente
				if (altezza.getText().toString().length() == 0 || (Integer.parseInt(altezza.getText().toString()) > MAXHEIGHT)
						|| (Integer.parseInt(altezza.getText().toString()) < MINHEIGHT)) {
					altezzaOk = false;
					height.setTextColor(Color.RED);
				} else {
					height.setTextColor(Color.WHITE);
					values.put(op.ALTEZZA, altezza.getText().toString());
				}

				// impongo peso minimo e massimo dichiarabile dall'utente
				if (peso.getText().toString().length() == 0 || (Integer.parseInt(peso.getText().toString()) < MINWEIGHT)
						|| (Integer.parseInt(peso.getText().toString())) > MAXWEIGHT) {
					pesoOk = false;
					weight.setTextColor(Color.RED);
				} else {
					weight.setTextColor(Color.WHITE);
					values.put(op.PESO, peso.getText().toString());
				}

				if (nomeOk && dataOk && altezzaOk && pesoOk) {
					// aggiorna tupla
					if (nomeProfilo != null) {
						db.update(op.TABLE1, values, "nome='" + nomeProfilo + "'", null);
						Intent intent = new Intent();
						setResult(RESULT_OK, intent);
						finish();
					}
					// inserisci tupla
					else {
						try {
							db.insertOrThrow(op.TABLE1, null, values);
							Intent intent = new Intent();
							setResult(RESULT_OK, intent);
							finish();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				db.close();
			}
		});
	}
}
